﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using Microsoft.SharePoint;

namespace RSM.Business
{
    public class XmlGenerator
    {
        public XmlGenerator ()
         {
         }
        FileManager fileManager = new FileManager();
        public List<Fields> GenerateXml(string columnFeature, string contentFeature, string colDesc, string contentDesc, string colScope, string conScope)
        {
            DataTable dt = Xmlreader.GetXML();
            string xml = string.Empty;
            List<XElement> columnsList = new List<XElement>();
            List<XElement> contentTypesList = new List<XElement>();
            foreach (DataRow row in dt.Rows)
            {
                foreach (DataColumn column in dt.Columns)
                {
                    if (row[column].ToString().StartsWith("<Field"))
                    {
                        xml = row[column].ToString();
                        columnsList.Add(GetElement(xml));
                    }
                    if (row[column].ToString().StartsWith("<ContentType"))
                    {
                        xml = row[column].ToString();
                        contentTypesList.Add(GetElement(xml));
                    }
                }
            }
            string path = "C://RSMTechnoFiles/";
            string siteColumnFolderPath = path + columnFeature + "/";
            string siteContentFolderPath = path + contentFeature + "/";
            string siteColumnFileName = "SiteColumns.xml";
            string siteContentFileName = "ContentTypes.xml";

            fileManager.CreateFolder(siteColumnFolderPath);
            fileManager.CreateFolder(siteContentFolderPath);
            List<SiteColCollection> siteCol = GenerateSiteColumnXmlFile(columnsList, siteColumnFolderPath + siteColumnFileName);
            List<Fields> fileds = GenerateXmlFile(contentTypesList, siteContentFolderPath + siteContentFileName, siteCol);
            fileManager.GenerateFeatureFile(siteColumnFolderPath, siteColumnFileName, columnFeature, colDesc, colScope);
            fileManager.GenerateFeatureFile(siteContentFolderPath, siteContentFileName, contentFeature, contentDesc, conScope);
            return fileds;
        }
        private List<Fields> GenerateXmlFile(List<XElement> list, string fileName, List<SiteColCollection> siteCol)
        {
            string pageName = string.Empty;
            string contentTypeId = string.Empty;
            XNamespace ns = "http://schemas.microsoft.com/sharepoint/";
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-16", "true"));
            XElement Elements = new XElement(ns + "Elements");
            List<XAttribute> pageAttributes = new List<XAttribute>();
            List<Fields> fieldNames = new List<Fields>();
            foreach (XElement ele in list)
            {
                if (ele.ToString().StartsWith("<ContentType"))
                {
                    XName cName = "Name";
                    XAttribute attrib = ele.Attribute(cName);
                    pageName = attrib.Value;
                    XName xId = "ID";
                    XAttribute idAttrib = ele.Attribute(xId);
                    contentTypeId = idAttrib.Value;

                }
                ele.SetAttributeValue("WebId", null);
                ele.SetAttributeValue("Version", null);
                ele.SetAttributeValue("UserSelectionMode", null);
                ele.SetAttributeValue("UserSelectionScope", null);

                //foreach (XElement el in ele.DescendantsAndSelf())
                //{
                fieldNames.Add(new Fields { Type = "pageName", FieldName = pageName });
                fieldNames.Add(new Fields { Type = "contentTypeID", FieldName = contentTypeId });

                foreach (XElement elem in ele.DescendantsAndSelf())
                {
                    elem.Name = ns.GetName(elem.Name.LocalName);
                    List<XAttribute> atList = elem.Attributes().ToList();

                    if (elem.ToString().StartsWith("<FieldRef"))
                    {
                        XName name = "ID";
                        XAttribute attrib = elem.Attribute(name);
                        if (attrib != null)
                        {
                            string id = attrib.Value;

                            XName fieldName = "Name";
                            XAttribute fieldAtt = elem.Attribute(fieldName);


                            XName type = "Type";
                            XAttribute typeAtt = elem.Attribute(type);

                            string fieldN = fieldAtt.Value;

                            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                            {
                                using (SPWeb web = site.RootWeb)
                                {
                                    SPFieldCollection collection = web.Fields;
                                    foreach (SPField field in collection)
                                    {
                                        string fieldId = field.Id.ToString();
                                        fieldId = "{" + fieldId + "}";
                                        if (fieldId == id)
                                        {
                                            if (fieldN != "ContentType")
                                            {
                                                if (field.Type.ToString() != "Invalid")
                                                {
                                                    fieldNames.Add(new Fields { Type = field.Type.ToString(), FieldName = fieldN });
                                                }
                                                else
                                                {
                                                    fieldNames.Add(new Fields { Type = field.TypeAsString, FieldName = fieldN });

                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            //foreach (SiteColCollection item in siteCol)
                            //{
                            //    if (item.Id == id)
                            //    {
                            //        fieldNames.Add(new Fields { Type = item.Type, FieldName = field });
                            //    }
                            //}
                        }
                        //}
                    }


                    //ele.Attributes().Remove();
                    // foreach (XAttribute at in atList)
                    // ele.Add(new XAttribute(at.Name.LocalName, at.Value));

                }
                Elements.Add(ele);

            }

            foreach (XNode node in Elements.Nodes())
            {
                if (node.NodeType == XmlNodeType.Element)
                {
                    foreach (XNode node2 in ((XElement)node).Nodes())
                    {
                        if (node2.ToString().StartsWith("<XmlDocuments"))
                        {
                            node2.Remove();
                        }
                    }
                }
            }
            doc.Add(Elements);
            doc.Save(fileName);
            return fieldNames;
            // CreatePageLayout(pageName, fieldNames);
        }
    
        private List<SiteColCollection> GenerateSiteColumnXmlFile(List<XElement> list, string fileName)
        {

            XNamespace ns = "http://schemas.microsoft.com/sharepoint/";
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-16", "true"));
            XElement Elements = new XElement(ns + "Elements");
            List<XAttribute> pageAttributes = new List<XAttribute>();
            List<SiteColCollection> fieldNames = new List<SiteColCollection>();
            foreach (XElement ele in list)
            {
                ele.SetAttributeValue("WebId", null);
                ele.SetAttributeValue("Version", null);
                ele.SetAttributeValue("UserSelectionMode", null);
                ele.SetAttributeValue("UserSelectionScope", null);

                foreach (XElement el in ele.DescendantsAndSelf())
                {
                    el.Name = ns.GetName(el.Name.LocalName);
                    List<XAttribute> atList = el.Attributes().ToList();

                    XName name = "Type";
                    XAttribute attrib = el.Attribute(name);
                    if (attrib != null)
                    {
                        string type = attrib.Value;

                        XName id = "ID";
                        XAttribute fieldAtt = el.Attribute(id);
                        string fieldId = fieldAtt.Value;

                        fieldNames.Add(new SiteColCollection { Type = type, Id = fieldId });
                    }
                    el.Attributes().Remove();
                    foreach (XAttribute at in atList)

                        el.Add(new XAttribute(at.Name.LocalName, at.Value));
                }
                Elements.Add(ele);
            }
            doc.Add(Elements);
            doc.Save(fileName);
            return fieldNames;
            // CreatePageLayout(fieldNames);
        }
    
        public static XElement GetElement(string xml)
        {
            XElement element = null;
            byte[] columnStream = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(xml);
            MemoryStream inStream = new MemoryStream(columnStream);
            XmlReader reader = XmlReader.Create(inStream); ;
            element = XElement.Load(reader);
            return element;
        }
   
    }
}
